package com.screen.screendisplay.service.impl.dryport;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.dryport.DryportProdoperGoodsSend;
import com.screen.screendisplay.mapper.dryport.DryportProdoperGoodsSendMapper;
import com.screen.screendisplay.service.dryport.DryportProdoperGoodsSendService;
import com.screen.screendisplay.vo.wholeproduct.RailwayGoodsSendVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 货物发送情况表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-09-25
 */
@Service
public class DryportProdoperGoodsSendServiceImpl extends ServiceImpl<DryportProdoperGoodsSendMapper, DryportProdoperGoodsSend> implements DryportProdoperGoodsSendService {

    @Autowired
    private DryportProdoperGoodsSendMapper goodsSendMapper;

    @Override
    public List<DryportProdoperGoodsSend> getMonthlyStatsByYear(Integer year) {
        return goodsSendMapper.getMonthlyStatsByYear(year);
    }

    @Override
    public List<DryportProdoperGoodsSend> getLatestMonthlyStats() {
        return goodsSendMapper.getLatestMonthlyStats();
    }

    @Override
    public List<DryportProdoperGoodsSend> getStatsByYearAndMonth(Integer year, Integer month) {
        return goodsSendMapper.getStatsByYearAndMonth(year, month);
    }

    @Override
    public DryportProdoperGoodsSend getStatsByDate(Integer year, Integer month, Integer day) {
        return goodsSendMapper.getStatsByDate(year, month, day);
    }

    @Override
    public List<RailwayGoodsSendVO> getRailwayGoodsSendAnnual(Integer year) {
        List<RailwayGoodsSendVO> resultList = new ArrayList<>();
        
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();
        
        // 查询最近5年的数据
        for (int i = 4; i >= 0; i--) {
            int targetYear = currentYear - i;
            
            // 查询目标年份的所有月份数据
            LambdaQueryWrapper<DryportProdoperGoodsSend> query = new LambdaQueryWrapper<>();
            query.eq(DryportProdoperGoodsSend::getYear, targetYear);
            
            // 如果是当前年份，只查询到当前月份
            if (targetYear == currentYear) {
                query.le(DryportProdoperGoodsSend::getMonth, currentMonth);
            }
            
            List<DryportProdoperGoodsSend> yearDataList = this.list(query);
            
            if (!yearDataList.isEmpty()) {
                RailwayGoodsSendVO vo = new RailwayGoodsSendVO();
                vo.setYear(targetYear);
                
                // 汇总年度计划量和完成量（累加各月数据）
                BigDecimal totalPlan = yearDataList.stream()
                        .map(DryportProdoperGoodsSend::getGoodsSendPlan)
                        .filter(plan -> plan != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                BigDecimal totalCompleted = yearDataList.stream()
                        .map(DryportProdoperGoodsSend::getGoodsSendAc)
                        .filter(ac -> ac != null)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                vo.setRailwayPlannedVolume(totalPlan.setScale(2, RoundingMode.HALF_UP));
                vo.setRailwayCompletedVolume(totalCompleted.setScale(2, RoundingMode.HALF_UP));
                
                // 计算同比率：需要去年同期的完成量
                int lastYear = targetYear - 1;
                LambdaQueryWrapper<DryportProdoperGoodsSend> lastYearQuery = new LambdaQueryWrapper<>();
                lastYearQuery.eq(DryportProdoperGoodsSend::getYear, lastYear);
                
                // 如果是当前年份，去年也只查询到对应的月份
                if (targetYear == currentYear) {
                    lastYearQuery.le(DryportProdoperGoodsSend::getMonth, currentMonth);
                }
                
                List<DryportProdoperGoodsSend> lastYearDataList = this.list(lastYearQuery);
                
                if (!lastYearDataList.isEmpty()) {
                    BigDecimal lastYearCompleted = lastYearDataList.stream()
                            .map(DryportProdoperGoodsSend::getGoodsSendAc)
                            .filter(ac -> ac != null)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    
                    // 同比率(%) = (今年完成量 - 去年完成量) / 去年完成量 * 100
                    if (lastYearCompleted.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal yoyRate = totalCompleted.subtract(lastYearCompleted)
                                .divide(lastYearCompleted, 4, RoundingMode.HALF_UP)
                                .multiply(new BigDecimal("100"))
                                .setScale(2, RoundingMode.HALF_UP);
                        vo.setYoyRate(yoyRate);
                    }
                }
                
                resultList.add(vo);
            }
        }
        
        return resultList;
    }
}
